package com.adinnet.core.exception;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Objects;

import static com.baomidou.mybatisplus.extension.api.R.failed;

/**
 * Created by sunjianbo on 2018/3/18 0018.
 */
@Slf4j
//@ControllerAdvice("com.adinnet")
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public R bizExceptionHandler(HttpServletResponse response, BizException ex){
        log.error(ex.getMessage(),ex);
        return failed(ex.getMessage());

    }

    /**
     * 处理Exception
     *
     * @param req
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R Exception(HttpServletRequest req, Exception ex, HttpServletResponse response) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ex.printStackTrace(new PrintStream(byteArrayOutputStream));
        String exception = byteArrayOutputStream.toString();
        log.error("服务器异常");
        log.error(">>>>>>>>>>>" + req.getRequestURI() + ">>>>>>>>>>>" + exception);
        log.error(ex.getMessage(),ex);
        if (ex instanceof IException) {
            failedResult( ((IException) ex).getCode(), ex.getMessage(),null);
        } else if (ex instanceof UnauthorizedException) {
            failedResult( 403,"没有访问权限",null);
        }
        return failed("服务器异常");
    }

    public R failedResult(Integer code,String msg,String data){
        IErrorCode errorCode=new IErrorCode() {
            @Override
            public long getCode() {
                return code;
            }

            @Override
            public String getMsg() {
                return msg;
            }
        };
        return R.restResult(data,errorCode);
    }

    /**
     * 捕捉validate异常  取出message信息响应
     *
     * @param e 异常
     * @return 响应结果
     * @throws Exception 重新抛出
     */
    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    public R bindException(Exception e) throws Exception {
        if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            return failed(Objects.requireNonNull(bindException.getFieldError()).getDefaultMessage());
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(EntityBody.<Void, String>builder().message(Objects.requireNonNull(bindException.getFieldError()).getDefaultMessage()).build());
        }

        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            StringBuilder builder = new StringBuilder();
            methodArgumentNotValidException.getBindingResult().getAllErrors()
                    .parallelStream().forEachOrdered(objectError -> builder.append(objectError.getDefaultMessage()).append("! "));
            return failed(builder.toString());
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(EntityBody.<Void, String>builder().message(builder.toString()).build());
        }
        throw e;
    }

}
